using UnityEngine;
using System.Collections;

public class RandomizeOrder : MonoBehaviour {
	
	public GameObject[] spheres = new GameObject[7];
	public int levelOfGuess = 3;
	protected int[] generatedOrder = new int[100];
	protected static int score = 0;
	protected string gameState = "generateOrder";
	protected bool computerTurn = true;
	protected int pressCount = 0;
//	public Texture2D statusArea;
    public GUIStyle myStyleScore;
    public GUIStyle myStyleHelp;
	int i;
	private bool btnDown = false;
	
	// Use this for initialization
	void OnGUI() 
	{ 
//		GUI.DrawTexture(new Rect(Screen.width/2-93, 21, Screen.width/2-52, 30), statusArea);
		if(gameState == "generateOrder") {
			GUI.Label(new Rect(Screen.width-210, 10, 200, 50), "Odota...", myStyleHelp);
		}
		if( !computerTurn && gameState == "yourTurn") {
			GUI.Label(new Rect(Screen.width-210, 10, 200, 50), "Sinun vuorosi", myStyleHelp);
		}
		GUI.Label(new Rect(10, 10, 200, 50), "Pisteesi: " + score, myStyleScore);
	}
	
	void Start ()
	{
		// Keep the mobile screen active all the time.
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
		
		GameObject.Find("GameOverText").guiText.enabled = false;
	    score = 0;
	}
	
	void Update () 
	{
		// Exit if native Back-button is clicked
        if( Input.GetKeyDown(KeyCode.Escape) ) {
            Application.LoadLevel("Menu");
        }
		
		if(gameState == "generateOrder" && computerTurn) {
			StartCoroutine( SelectSphere() );
			computerTurn = false;
		}
	}
	
	IEnumerator BeenHit(GameObject obj) {
		if( !computerTurn && gameState == "yourTurn" && !btnDown ) {
			btnDown = true;
			int sphereNum = System.Convert.ToInt32( obj.name.Substring(6) );
			pressCount++;
		
			obj.transform.Translate (0, -0.2f, 0);
			yield return new WaitForSeconds(0.3f);
			obj.transform.Translate (0, 0.2f, 0);
			
			if(generatedOrder[pressCount] == sphereNum) { // oikein arvattu
				score += 20;
			} else { // väärin arvattu
				GM.LastScore = score;
				GameObject.Find("GameOverText").guiText.enabled = true;
				yield return new WaitForSeconds(2);
				Application.LoadLevel("GameOver");	
			}
			
			if(pressCount == levelOfGuess-1) { // taso suoritettu
				gameState = "generateOrder";
				computerTurn = true;
			}
			btnDown = false;
		} 
		else 
			yield break;
	}
	
	IEnumerator SelectSphere() 
	{
		yield return new WaitForSeconds(1.0f);
		for(i=1; i<=levelOfGuess; i++)
		{
			generatedOrder[i] = Random.Range(1, 6);
			
			yield return new WaitForSeconds(0.5f);
			spheres[ generatedOrder[i] ].transform.Translate(0, -0.2f, 0);
			yield return new WaitForSeconds(0.5f);
			spheres[ generatedOrder[i] ].transform.Translate(0, 0.2f, 0);
		}
		levelOfGuess++;
		gameState = "yourTurn";
		pressCount = 0;
	}
	
}
